<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2023/3/14
 * Time: 15:01
 */

namespace App\Rep;


use App\Events\OrderChildAllDone;
use App\Models\ModelFields;
use App\Models\Models;
use App\Models\Order;
use App\Models\OrderAudit;
use App\Models\OrderAuditLog;
use App\Models\OrderChild;
use App\Models\Product;
use App\Models\ProductJobType;
use App\Models\Specification;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use function Symfony\Component\Routing\Matcher\Dumper\export;

class OrderRep
{

    /**
     * 获取订单列表
     * @param $params
     * @return mixed
     */
    public function getOrderListRep($params){
        $list = Order::Search($params)
            ->with(['color'=>function($q){
                return $q->select('id','color');
            },'product'=>function($q){
                return $q->select('id','product_name');
            },'customer'=>function($q){
                return $q->select('id','customer_name','customer_address','logistics');
            },'modelNumber'=>function($q){
                return $q->select('id','model_number','file_id')->with(['specification','file']);
            },'orderChild'=>function($q){
                return $q->with(['job_type','employee']);
            },'specification'=>function($q){
                return $q->select('id','specification');
            },'accountExecutive'=>function($q){
                return $q->select('id','company_name','phone');
            },'finish_product'=>function($q){
                return $q->select('order_id','num','warehouse_id','goods_shelf_id');
            },'admin_user'=>function($q){
                return $q->select('id','company_name');
            }])
            ->orderBy('id','desc')
            ->paginate($params['per_page']??10)->toArray();
        $data = $list['data'];
        if($data){
            foreach($data as $k=>$v){
                $product_id = $v['product_id'];
                $modelid = Product::where('id',$product_id)->value('modelid');
                $tablename = Models::where('modelid',$modelid)->value('tablename');
                $model_field = ModelFields::where('modelid',$modelid)->get();

                if($model_field){
                    foreach($model_field as $kk=>$vv){
                        if(in_array($vv->formtype,['input','textarea','inputnumber'])){
                            $data[$k]['models_field'][$vv->field] = DB::table($tablename)->where('order_id',$v['id'])->value($vv->field);
                        }else{
                            if(!empty($vv->option_list)){
                                $option_list = explode("\n",$vv->option_list);
                                //p($option_list);
                                $option_arr = [];
                                foreach($option_list as $key=>$val){
                                    $option = explode("|",rtrim($val));
                                    //p($option);
                                    $option_arr[$option[1]] = $option[0];
                                }
                                $field_key = DB::table($tablename)->where('order_id',$v['id'])->value($vv['field']);
                                $data[$k]['models_field'][$vv->field] = $field_key;
                                $data[$k]['models_field'][$vv->field."s"] = $option_arr[$field_key]??'';
                                //$data[$k]['models_field'][$vv->field] = ['value'=>$option_arr[$field_key]??'','key'=>$field_key];
                            }else{
                                $data[$k]['models_field'][$vv->field] = DB::table($tablename)->where('order_id',$v['id'])->value($vv['field']);
                            }
                        }
                    }
                }

            }
        }
        $list['data'] = $data;
        return $list;
    }

    /**
     * 添加订单
     * @param $params
     * @return Order|array
     */
    public function createOrderRep($params){
        DB::beginTransaction();
        try {
            $product = Product::where('id',$params['product_id'])->first();
            if(empty($product->modelid)){
                return ['code'=>2001,'data'=>[],'msg'=>'产品没有绑定模型'];
            }
            $models = Models::where('modelid',$product->modelid)->first();
            $modelRep = new ModelRep();
            $field_arr = $modelRep->getProductFieldListRep($params);
            //p($field_arr);

            $insarr=[];
            $insarrs = [];
            if(isset($params['id']) && !empty($params['id'])){
                foreach($field_arr as $k=>$v){
                    if($v['is_default'] == 1){
                        $insarr[$v['field']] = $params[$v['field']]??'';
                        //是否备货
                        if($v['field'] == 'is_stock_up'){
                            if($params['is_stock_up'] == 1){
                                $insarr['customer_id'] = 0;
                            }
                        }
                        //是否是补录订单
                        if($v['field'] == 'is_replenishment'){
                            if($params['is_replenishment'] == 1){
                                $insarr['status'] = 1;
                                $insarr['production_status'] = 3;
                            }
                        }
                    }else{
                        if(isset($params[$v['field']]) && !empty($params[$v['field']])){
                            $insarrs[$v['field']] =$params[$v['field']]??'';
                        }
                    }

                }
                //p($insarr);

                unset($insarr['user_id']);
                unset($insarr['order_number']);
                unset($insarr['serial_number']);
                //p($models->tablename);
                Order::where('id',$params['id'])->update($insarr);
                $model = Order::find($params['id']);
                if(!empty($insarrs)){
                    DB::table($models->tablename)->where('order_id',$params['id'])->update($insarrs);
                }
            }else{

                foreach($field_arr as $k=>$v){
                    if($v['is_default'] == 1){
                        $insarr[$v['field']] =$params[$v['field']]??'';
                        //是否备货
                        if($v['field'] == 'is_stock_up'){
                            if($params['is_stock_up'] == 1){
                                $insarr['customer_id'] = 0;
                            }
                        }
                        //是否是补录订单
                        if($v['field'] == 'is_replenishment'){
                            if($params['is_replenishment'] == 1){
                                $insarr['status'] = 1;
                                $insarr['production_status'] = 3;
                            }
                        }
                    }else{
                        if(isset($params[$v['field']]) && !empty($params[$v['field']])){
                            $insarrs[$v['field']] =$params[$v['field']]??'';
                        }
                    }

                }

                $is_has_order_number = Order::where('order_number',$params['order_number'])->first();
                if($is_has_order_number){
                    return ['code'=>2001,'data'=>[],'msg'=>'订单号已存在！'];
                }
//                $is_has_serial_number = Order::where('serial_number',$params['serial_number'])->first();
//                if($is_has_serial_number){
//                    return ['code'=>2001,'data'=>[],'msg'=>'流水号已存在！'];
//                }
                $insert_id = Order::insertGetId($insarr);
                $insarrs['order_id'] =$insert_id;
                DB::table($models->tablename)->insert($insarrs);
                $model = Order::find($insert_id);
            }

            //p($model);
            if($params['is_replenishment'] == 1){
                //补录订单，直接加入成品库
                $seniFinishProductRep = new SemiFinishProductRep();
                $seniFinishProductRep->replenishmentAddFinishProductRep($model,$params['num'],$params['warehouse_id'],$params['goods_shelf_id']);
            }else{
                //订单审核
                //判断审核流程，是否对订单进行审核
                $orderAuditList = self::judgeOrderAudit();
                if($orderAuditList){
                    //添加审核记录
                    self::createOrderAudit($orderAuditList,$model->id,$params['user_id'],$params['username'],$params['role_id'],$params['role_name'],$params['remark']);
                }
            }

            DB::commit();
            return ['code'=>0,'data'=>$model,'msg'=>'success'];
        }catch(\Exception $e){
            DB::rollBack();
            return ['code'=>2001,'data'=>[],'msg'=>$e->getMessage()];
        }
    }

    /**
     * 删除订单
     * @param $params
     */
    public function delOrderRep($params){
        $model = Order::where('id',$params['id'])->first();
        $model->is_del = 1;
        $model->save();
        $order_child = OrderChild::where('order_id',$params['id'])->update(['is_del'=>1]);
        return $model;
    }

    /**
     * 审核订单
     * status 1：已审核通过2：未审核3：已审核不通过
     * @param $params
     */
    public function auditOrderRep($params){

        DB::beginTransaction();
        try{
            $model = Order::where('id',$params['id'])->first();
            $orderAuditLog = OrderAuditLog::where('order_audit_name',$params['field'])->where('order_id',$params['id'])->first();
            $field = $params['field'];
            $model->$field = $params['status'];
            $orderAudit = OrderAudit::where('status',1)->orderBy('sort','desc')->first();
            $last_field = $orderAudit->field_name;
//            if($field == 'financial_status'){
//                if($params['status'] == 1){
//                    $model->status = 1;
//                }
//            }
            if($field == $last_field){
                if($params['status'] == 1){
                    $model->status = 1;
                    //自动生成子订单
                    $childOrderRep = new OrderChildRep();
                    $childOrderRep->autoCreateOrderChild($model->product_id,$model->id,$model->model_number_id,$model->specification_id);
                }
            }
            if($params['status'] == 2){
                $model->status = 3;
            }
            $model->save();
            $orderAuditLog->res = $params['status'];
            $orderAuditLog->remark = $params['remark']??'审核原因';
            $orderAuditLog->save();
            DB::commit();
            return $model;
        }catch(\Exception $exception){
            DB::rollBack();
            return ['code'=>2001,'data'=>[],'msg'=>$exception->getMessage()];
        }

    }


    /**
     * 在子订单完成提交的时候调用,加入半成品库
     * 查询子订单状态
     */
    public function selectOrderChildStatus($order_id){
        $count = OrderChild::where('order_id',$order_id)->where('status','<>',1)->count();
        if(!$count){
            //加入半成品库
            $order = Order::where('id',$order_id)->first();
            $order->production_status = 2;
            $order->save();
            event(new OrderChildAllDone($order));

            (new FinishProductRep())->addFinishProductRep(
                $order_id,
                $order->num,
                $order->warehouse_id,
                $order->goods_shelf_id,
                $order->model_number_id,
                $order->specification_id,
                $order->color_id,
                $order->direction,
                $order->customer_id,
                $order->is_stock_up,
                $image_arr = []
            );
        }
    }

    /**
     * 获取审核订单列表
     * @param $params
     */
    public function getAuditOrderListRep($params){
        $list = Order::Audit($params)
            ->with(['color'=>function($q){
                return $q->select('id','color');
            },'product_name'=>function($q){
                return $q->select('id','product_name');
            },'customer'=>function($q){
                return $q->select('id','customer_name');
            },'modelNumber'=>function($q){
                return $q->select('id','model_number','file_id')->with(['specification','file']);
            },'accountExecutive',
                'specification'=>function($q){
                    return $q->select('id','specification');
                },'audit_log'=>function($q){
                    $q->where('status',1);
                }])
            ->orderBy('status','asc')
            ->orderBy('id','desc')
            ->paginate($params['per_page']??10)->toArray();

        $data = $list['data'];
        if($data){
            foreach($data as $k=>$v){
                $product_id = $v['product_id'];
                $modelid = Product::where('id',$product_id)->value('modelid');
                $tablename = Models::where('modelid',$modelid)->value('tablename');
                $model_field = ModelFields::where('modelid',$modelid)->get();

                if($model_field){
                    foreach($model_field as $kk=>$vv){
                        if(in_array($vv->formtype,['input','textarea','inputnumber'])){
                            $data[$k]['models_field'][$vv->field] = DB::table($tablename)->where('order_id',$v['id'])->value($vv['field']);
                        }else{
                            if(!empty($vv->option_list)){
                                $option_list = explode("\n",$vv->option_list);
                                //p($option_list);
                                $option_arr = [];
                                foreach($option_list as $key=>$val){
                                    $option = explode("|",rtrim($val));
                                    //p($option);
                                    $option_arr[$option[1]] = $option[0];
                                }
                                $field_key = DB::table($tablename)->where('order_id',$v['id'])->value($vv['field']);
                                $data[$k]['models_field'][$vv->field] = $field_key;
                                //$data[$k]['models_field'][$vv->field] = ['value'=>$option_arr[$field_key]??'','key'=>$field_key];
                            }else{
                                $data[$k]['models_field'][$vv->field] = DB::table($tablename)->where('order_id',$v['id'])->value($vv['field']);
                            }
                        }
                    }
                }

            }
        }
        $list['data'] = $data;
        return $list;
    }

    /**
     * 获取订单审核流程
     * @param $params
     */
    static public function getOrderAuditFlowRep(){
        return OrderAudit::where('status',1)->orderBy('sort','desc')->get();
    }


    /**
     * 判断是否对订单进行审核
     * @return bool
     */
    static function judgeOrderAudit(){
        $orderAuditList = self::getOrderAuditFlowRep();
        if($orderAuditList->count()){
            return $orderAuditList;
        }
        return false;
    }

    /**
     * 添加审核记录
     * @param OrderAudit $list
     * @param $order_id
     * @param $user_id
     * @param $user_name
     * @param $role_id
     * @param $role_name
     * @param $remark
     */
    static function createOrderAudit($list,$order_id,$user_id,$user_name,$role_id,$role_name,$remark){
        foreach($list as $k=>$v){
            //添加审核记录
            OrderAuditLog::updateOrCreate(['order_id'=>$order_id,'audit_name'=>$v->audit_name],
                [
                    //'order_id'=>$order_id,
                    'user_id'=>$user_id,
                    'user_name'=>$user_name,
                    'role_id'=>$role_id,
                    'role_name'=>$role_name,
                    'order_audit_name'=>$v->field_name,
                    'audit_name'=>$v->audit_name,
                    'order_audit_id'=>$v->id,
                ]);
        }
    }

    /**
     * 设置订单的生产状态
     */
    public function setOrderProductionStatus($order_id,$production_status){
        $order = Order::where('id',$order_id)->first();
        $order->production_status = $production_status;
        $order->save();
        return $order;
    }

    //自动生成流水号
    public function automaticGenerationSerialNumberRep($int = 1){
        $rule = \App\Models\RuleSerialNumber::first();
        $prefix = $rule->prefix_custom;
        if($rule->date == 1){
            $date = date("Y");
        }
        if($rule->date == 2){
            $date = date("Ym");
        }
        if($rule->date == 3){
            $date = date("Ymd");
        }
        $count = Order::whereBetween('created_at',[date('Y-m-d 00:00:00'),date('Y-m-d 23:59:59')])->count();
        $number = str_pad($count+$int,$rule->serial_number,"0",STR_PAD_LEFT);
        $serialNumber = $prefix.$date.$number;


        $info = Order::where('serial_number',$serialNumber)->first();
        if($info){
            $int = $int + 1;
            $serialNumber = $this->automaticGenerationSerialNumberRep($int);
        }
        //p($int);
        return $serialNumber;
    }

    //自动生成订单号
    public function automaticGenerationOrderNumberRep($int = 1){
        $order = Order::where('is_del',2)->orderBy('id','desc')->first();
//        if($order){
//            $order_number = $order->order_number;
//            //$order_number = "abcdef";
//            preg_match_all('/\d+/', $order_number, $result);
//            if(!empty($result[0])){
//                $old_num = $result[0][count($result[0])-1];
//                //p($old_num);
//                $new_num = $old_num +1;
//                $str = str_replace($old_num,$new_num,$order_number);
//                //p($str);
//            }else{
//                $str = $order_number."1";
//            }
//        }else{
//            $str='001';
//        }
        $order_number = $order->order_number+$int;
        $info = Order::where('order_number',$order_number)->first();
        if($info){
            $int = $int + 1;
            $order_number = $this->automaticGenerationOrderNumberRep($int);
        }

        return $order_number;
    }

    /**
     * 是否已收余款
     * @param $params
     * @return void
     */
    public function setIsResidualPaymentRep($params){
        $model = Order::find($params['order_id']);
        $product_id = $model->product_id;
        $modelid = Product::where('id',$product_id)->value('modelid');
        $tablename = Models::where('modelid',$modelid)->value('tablename');
        $res = DB::table($tablename)->where('order_id',$params['order_id'])->update(['is_residual_payment'=>$params['is_residual_payment']]);
        return $res;
    }

}
